import sys
import subprocess


def printHelp(command):
    if command == '-a':
        print("-a: 文件新增配置：file_path, config_content")
        print( "ChangeFile.py -t '{file_path}' '{config_content}' ")
        exit(0)
    elif command == '-c':
        print("-c: 文件替换：new_file_path, local_path ")
        print( "ChangeFile.py -c '{new_file_path}' '{local_path}' ")
        exit(0)
    else:
        print("Use: ChangeFile.py -[a|c]")
        print("-a: 文件新增配置：file_path, config_content")
        print("ChangeFile.py -t '{file_path}' '{config_content}' ")

        print("-c: 文件替换：local_path, new_file_path")
        print("ChangeFile.py -c '{local_path}' '{new_file_path}' ")

        exit(0)

DEFAULT_ROOT = "/Users/"
def addFileConfigContent(file_path,config_content):
    try:
        with open(f'{DEFAULT_ROOT}{getUserInfo()}/{file_path}', 'r', encoding='utf-8') as f:
            content = f.read()
            if config_content in content:
                print(f"已存在:{config_content}")
            else:
                # 修改配置文件
                with open(f'{DEFAULT_ROOT}{getUserInfo()}/{file_path}', 'a', encoding='utf-8') as f:
                    f.write("\n")
                    f.write(f"{config_content}")
    except Exception as e:
        print(f"读取file_content失败：{e}")
        exit(0)

    print(f"file_path： {file_path}")

    try:
        with open(f'{DEFAULT_ROOT}{getUserInfo()}/{file_path}', 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"file_content:{content}")
    except Exception as e:
        print(f"读取file_content失败：{e}")
        exit(0)

def copyFileConfigContent(new_file_path,local_path):
    print(f"本地文件1：{getUserInfo()}")
    path = f'{DEFAULT_ROOT}{getUserInfo()}/{local_path}'
    print(f"本地文件：{path}")
    try:
        subprocess.run(['cp','-f',f'{new_file_path}',f'{path}'], capture_output=True, text=True)
    except Exception as e:
        print(f"复制文件失败：{e}")
        exit(0)

    try:
        with open(path, 'r', encoding='utf-8') as f:
            content = f.read()
            print(f"file_content:{content}")
    except Exception as e:
        print(f"读取file_content失败：{e}")
        exit(0)


def getUserInfo():
    result = subprocess.run(['whoami'], capture_output=True, text=True)
    print("获取用户信息:", result.stdout)
    return result.stdout.replace('\n','').replace('\t','')

def test():
    addFileConfigContent('.ohpm/.ohpmrc','//localhost:8088/repos/ohpm/:_auth=NWFmMTRlNDc0NzAyNDVmY2IwMzZkZGUwYmRhMzYyZjE=')
    #findFileNameType('/Users/gymd/DevEcoStudioProjects/hm-demo','/Users/gymd/Desktop/维护/cgmartsapp/android/app/build/outputs/apk','','app-release.apk')

if __name__ == "__main__":
    # test()
    if len(sys.argv) < 4:
        printHelp('error')
    command = sys.argv[1]
    print(f"参数长度：{len(sys.argv)}{sys.argv[0]}{sys.argv}")
    if command == "-a":
        if len(sys.argv) < 4:
            printHelp(command)
        addFileConfigContent( sys.argv[2], sys.argv[3])
    elif command == "-c":
        if len(sys.argv) < 4:
            printHelp(command)
        copyFileConfigContent(sys.argv[2], sys.argv[3])
    else:
        printHelp('error')

# python ChangeFile.py -a '.ohpm/.ohpmrc' '//localhost:8088/repos/ohpm/:_auth=NWFmMTRlNDc0NzAyNDVmY2IwMzZkZGUwYmRhMzYyZjE='
# python ChangeFile.py -c '/Users/gymd/Downloads/打包机/.ohpmrc' '.ohpmrc'
